package server

import (
	"dcim/pkg/generic-go-kit/handler/nats_micro"
	"fmt"
	"github.com/nats-io/nats.go"
	"github.com/nats-io/nats.go/micro"
	"log"
	"os"
	"syscall"
)

type NatsMicroServer struct {
	MicroConfig micro.Config
	ServerNats  *nats.Conn
	Handler     nats_micro.NatsMicroHandlerI
}

func (s *NatsMicroServer) Run() {

	srv, err := micro.AddService(s.ServerNats, s.MicroConfig)
	if err != nil {
		log.Fatal(err)
		return
	}

	s.Handler.RegisterHandlers(srv)

	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal, 1)
	// kill (no param) default send syscall.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall.SIGKILL but can't be catch, so don't need add it

	// 优雅退出（退出信号）
	waitElegantExit := func(signalChan chan os.Signal) {
		for i := range signalChan {
			switch i {
			case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
				// 这里做一些清理操作或者输出相关说明，比如 断开数据库连接
				fmt.Println("receive exit signal ", i.String(), ",exit...")
				fmt.Println("Server exiting")
				os.Exit(0)
			}
		}
	}

	waitElegantExit(quit)

	defer func() {
		if err := recover(); err != nil {

			if er, ok := err.(error); ok {
				fmt.Println("[Recover]: " + er.Error())
			} else {
				fmt.Println("[Recover]: " + er.Error())
			}

		}
	}()

}
